#!/bin/sh -x
PN=$(basename $0 )
TMPFILES=""
cleanup()
{
        for F in ${TMPFILES}; do
                /bin/rm -f ${F}
        done
}

mkTemp()
{
        FN=$( mktemp fgp.XXXXXX )
        TMPFILES="${TMPFILES} ${FN}"
        printf "%s\n" "${FN}"
}

usage() 
{
        printf "%s: %s\n" "${PN}" "${*}"
        printf "usage: %s file -o outputfile [--include=file ...]\n" \
                "${PN}" >&2
        cleanup
        exit 1
}

die()
{
        printf "%s: error editing. Has output changed?\n" "${PN}" >&2
        cleanup
        exit 2
}

[ ${#} -ge 3 ] || usage too few arguments.
[ "${2}" == "-o" ] || usage syntax error.
OF="${3}"
IF="${1}"
shift
shift
shift
[ -r "${IF}" ] || usage unable to open file.

T1=$(mkTemp)
touch ${T1}

NS=0
IC=0
while [ "$#" -ge 1 ]; do
    case "${1}" in
    --ignorecase) IC=1;;
    --ns*=*)
        printf "namespace %s\n{\n" "${1//-*=}" >> ${T1}
        NS=$(( ${NS} + 1 ))
        ;;

    --us*=*)
        printf "using %s;\n" "${1//-*=}" >> ${T1}
        ;;

    --i*=*)
        printf "#include \"%s\"\n" "${1//-*=}" >> ${T1}
        ;;
    *) ;;
    esac
    shift
done

T2=$(mkTemp)

if [ "${IC}" -eq 1 ]; then
    sed 's/str\[\([0-9][0-9]*\)\]/tolower(str[\1])/g' ${IF} >> ${T1} || die
    sed  's/^\([ 	]*\)if *(\*\([a-z][a-z]*\) *== *\*\([a-z][a-z]*\) *&& *!strncmp (\([^)]*\)).*$/\1 if (tolower(*\2) == *\3 \&\& !strncasecmp( \4 ))/g' ${T1} > ${T2}

else
    cat ${IF} >> ${T1}
    cat ${T1} > ${T2}
fi

# Close namespaces
while [ ${NS} -gt 0 ]; do printf "}\n" >> ${T2}; NS=$(( $NS - 1 )); done

cp ${T2} ${OF}

cleanup
exit 0
